﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using EraNet.Core;
using EraNet.Core.Events;
using EraNet.Core.Model.Account;
using EraNet.Core.Data;
using EraNet.Core.Caching;
using EraNet.Common;

namespace EraNet.Services.Account
{
    public class AdminMemberService : IAdminMemberService
    {
        #region Constants
        private const string ADMINMEMBER_BY_ID_KEY = "EraNet.AdminMember.Id-{0}";
        private const string ADMINMEMBER_PATTERN_KEY = "EraNet.AdminMember";
        #endregion
        #region Ctor
        private readonly IRepository<AdminMember> _adminmemberRepository;
        private readonly IRepository<AdminGroupMapping> _admingroupmapRepository;
        private readonly IRepository<AdminGroup> _admingroupRepository;
        private readonly ICacheManager _cacheManager;
        private readonly IEventPublisher _eventPublisher;
        /// <summary>
        /// 
        /// </summary>
        /// <param name="adminRepository"></param>
        /// <param name="cacheManager"></param>
        public AdminMemberService(IRepository<AdminMember> noticeRepository,IRepository<AdminGroupMapping> admingroupmapRepository,IRepository<AdminGroup> admingroupRepository, ICacheManager cacheManager, IEventPublisher eventPublisher)
        {
            _adminmemberRepository = noticeRepository;
            _admingroupmapRepository = admingroupmapRepository;
            _admingroupRepository = admingroupRepository;
            _cacheManager = cacheManager;
            _eventPublisher = eventPublisher;
        }
        #endregion
        #region Methods
        /// <summary>
        /// 根据用户名，用户密码，获取用户信息
        /// </summary>
        /// <param name="UserName">用户名</param>
        /// <param name="Pwd">用户密码</param>
        /// <param name="result">返回信息，1成功，0密码错误  2用户不存在 3用户被删除  4用户被锁定 5用户名格式不正确 6密码格式不正确 </param>
        /// <returns></returns>
        public AdminMember Login(string UserName, string Pwd, out int result)
        {
            #region pre
            result = -1;
            AdminMember member = null;
            UserName = UserName.Trim();
            Pwd = Pwd.Trim();
            #endregion
            #region operate
            if (string.IsNullOrEmpty(UserName)||!Validator.IsUserName(UserName)) result = 5;

            if (string.IsNullOrEmpty(Pwd)||!Validator.IsUserName(Pwd)) result = 6;

            if (result != -1) return member;

            member = _adminmemberRepository.Table.Where(c => c.AccountName.ToLower() == UserName.ToLower()).FirstOrDefault();
            //如果没有用户
            if (member == null)
            {
                result = 2;
                return member;
            }
            //检查用户状态
            switch (member.Status)
            {
                case 0:
                    result = 4;
                    break;
                case 2:
                    result = 3;
                    break;
            }
            //检测用户密码
            if(member.Password!=Utility.MD5(Pwd)) result=0 ;
            if (result != -1) return member;
            #endregion
            #region  success
            result = 1;
            //写入登陆的COOKIES
            Utility.WriteCookie(string.Format(ADMINMEMBER_BY_ID_KEY, member.Id), "");
            return member;
            #endregion
        }
        /// <summary>
        /// 插入新数据
        /// </summary>
        /// <param name="model"></param>
        /// <returns>1.插入成功 0.插入失败  2.用户已经存在  3.邮箱已经存在  </returns>
        public int Insert(AdminMember model)
        {
            if (model == null) throw new ExtException("NUll AdminMember Model");
            //判断邮箱是否存在
            if (_adminmemberRepository.Table.Where(c => c.Email.ToLower() == model.Email.Trim().ToLower()).Count() > 0) return 3;
            //用户名已经注册
            if(_adminmemberRepository.Table.Where(c=>c.AccountName.ToLower()==model.AccountName.Trim().ToLower()).Count()>0) return 2;

            int rs = _adminmemberRepository.Insert(model);
            if (rs > 0)
            {
                rs = 1;
                _cacheManager.RemoveByPattern(ADMINMEMBER_PATTERN_KEY);

                //event notification
                _eventPublisher.EntityInserted(model);
            }
            return rs;
        }
        /// <summary>
        /// 更新数据
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public bool Update(AdminMember model)
        {
            bool result = false;
            if (model == null) throw new ExtException("NUll AdminMember Model");
            if (_adminmemberRepository.Update(model) > 0)
            {
                result = true;
                //remove all cache by pattern key
                _cacheManager.RemoveByPattern(ADMINMEMBER_PATTERN_KEY);
                _eventPublisher.EntityUpdated(model);
            }
            return result;
        }
        /// <summary>
        /// 根据ID获取数据
        /// </summary>
        /// <param name="Id"></param>
        /// <returns></returns>
        public AdminMember GetAdminById(int adminMemberId)
        {
            if (adminMemberId <= 0) return null;
            string key = string.Format(ADMINMEMBER_BY_ID_KEY, adminMemberId);
            return _cacheManager.Get(key, () =>
            {
                var pv = _adminmemberRepository.GetById(adminMemberId);
                return pv;
            });
        }
        /// <summary>
        /// 分页获取
        /// </summary>
        /// <param name="PageIndex"></param>
        /// <param name="PageSize"></param>
        /// <param name="PageCount"></param>
        /// <returns></returns>
        public IList<AdminMapping> SelectPager(int PageIndex, int PageSize, out int PageCount)
        {
            var query = from c in _adminmemberRepository.Table
                        join fc in _admingroupmapRepository.Table.DefaultIfEmpty() on c.Id equals fc.MemberId
                        select new AdminMapping { 
                                 AccountName=c.AccountName,
                                 Address=c.Address,
                                 CreateDate=c.CreateDate,
                                 CreatedByUserID=c.CreatedByUserID,
                                 Email=c.Email,
                                 Id=c.Id,
                                 LastIPAddress=c.LastIPAddress,
                                 LastLoginDate=c.LastLoginDate,
                                 RealNames=c.RealNames,
                                 Sex=c.Sex,
                                 Status=c.Status,
                                 Telephone=c.Telephone,
                                 GroupName=(from p in _admingroupRepository.Table where p.Id==fc.GroupId select p.GroupName).FirstOrDefault()
                        };
            PageCount = query.Count();
            query = query.OrderByDescending(b => b.CreateDate);
            query = query.Skip((PageIndex - 1) * PageSize).Take(PageSize);
            return query.ToList();
        }
        /// <summary>
        /// 分页获取
        /// </summary>
        /// <param name="PageIndex"></param>
        /// <param name="PageSize"></param>
        /// <param name="Status"></param>
        /// <param name="CreatedByUserID"></param>
        /// <param name="PageCount"></param>
        /// <returns></returns>
        public IList<AdminMapping> SelectPager(int PageIndex, int PageSize, int Status, int CreatedByUserID, out int PageCount)
        {
            var query = from c in _adminmemberRepository.Table
                        join fc in _admingroupmapRepository.Table.DefaultIfEmpty() on c.Id equals fc.MemberId
                        select new AdminMapping
                        {
                            AccountName = c.AccountName,
                            Address = c.Address,
                            CreateDate = c.CreateDate,
                            CreatedByUserID = c.CreatedByUserID,
                            Email = c.Email,
                            Id = c.Id,
                            LastIPAddress = c.LastIPAddress,
                            LastLoginDate = c.LastLoginDate,
                            RealNames = c.RealNames,
                            Sex = c.Sex,
                            Status = c.Status,
                            Telephone = c.Telephone,
                            GroupName =""
                        };
            if (Status >= 0) query = query.Where(c => c.Status == Status);
            if (CreatedByUserID > 0) query = query.Where(c => c.CreatedByUserID == CreatedByUserID);
            PageCount = query.Count();
            query = query.OrderByDescending(b => b.CreateDate);
            query = query.Skip((PageIndex - 1) * PageSize).Take(PageSize);
            return query.ToList();
        }
        #endregion
    }
}
